package util;

import java.util.List;
import java.util.Random;

import solution.Solution;

/**
 * 通用工具类
 * 
 * @author Dehuai Liu
 *
 */
public class GeneralUtil {
	static Random random = new Random();

	/**
	 * 从目标范围中选取k个与targetIndex不同的索引
	 * 
	 * @param targetIndex
	 * @param k
	 * @param range
	 * @return
	 */
	public static int[] selectKId(int targetIndex, int k, int range) {
		// 选出k个索引
		int[] randomIndex = new int[k];
		for (int i = 0; i < k; i++) {
			randomIndex[i] = random.nextInt(range);
			boolean isUnique = false;
			while (!isUnique) {
				int j = 0;
				for (; j < i; j++) {
					if (randomIndex[i] == randomIndex[j] || randomIndex[i] == targetIndex) {
						// 重新生成一个索引
						randomIndex[i] = random.nextInt(range);
						break;
					}
				}

				// 没有重复
				if (j == i) {
					isUnique = true;
				}
			}
		}
		return randomIndex;
	}

	public static int[] selectKIndexFromTopHalf(int targetIndex, int k, List<Solution<Integer, Double>> population) {
		int[] indexArr = selectTopHalf(population);
		// 从indexArr中选出k个索引
		if (k > indexArr.length) {
			return null;
		} else if (k == indexArr.length) {
			return indexArr;
		} else {
			int[] result = new int[k];
			for (int i = 0; i < result.length; i++) {
				result[i] = indexArr[random.nextInt(indexArr.length)];
				boolean isUnique = false;
				while (!isUnique) {
					int j = i - 1;
					for (; j >= 0; j--) {
						if (result[i] == result[j]) {
							result[i] = indexArr[random.nextInt(indexArr.length)];
							break;
						}
					}
					if (j == -1) {
						break;
					}
				}
			}
			return result;

		}

	}

	/**
	 * 找到前一半最优的解
	 * 
	 * @param population
	 * @return
	 */
	public static int[] selectTopHalf(List<Solution<Integer, Double>> population) {
		Solution<Integer, Double>[] solutions = new Solution[population.size()];
		for (int i = 0; i < solutions.length; i++) {
			solutions[i] = population.get(i);
		}

		// 冒泡排序
		for (int i = 0; i < solutions.length / 2; i++) {
			for (int j = solutions.length - 1; j > i; j--) {
				if (solutions[j].getValue() < solutions[j - 1].getValue()) {
					Solution<Integer, Double> temp = solutions[j];
					solutions[j] = solutions[j - 1];
					solutions[j - 1] = temp;
				}
			}
		}
		int[] indexArr = new int[solutions.length / 2];
		for (int i = 0; i < solutions.length / 2; i++) {
			indexArr[i] = solutions[i].getId();
		}

		return indexArr;
	}

	public static double sigmoid(double value) {
		return 1 / (1 + Math.exp(-value));
	}
	
	public static void main(String[] args) {
		int Vmax=4;
		for(int i=-Vmax;i<=Vmax;i++) {
			System.out.println(i+":"+sigmoid(i));
		}
	}
}
